<!--
  文件管理组件
  
  提供文件导入、导出、编辑等功能
  支持多种文件格式的处理
-->

<template>
  <div class="file-manager">
    <!-- 页面标题 -->
    <div class="header">
      <h2>📁 文件管理器</h2>
      <p class="subtitle">导入、编辑和导出文件</p>
    </div>

    <!-- 操作按钮区域 -->
    <div class="actions">
      <button @click="importFile" class="btn btn-primary" :disabled="loading">
        📤 导入文件
      </button>
      <button @click="exportFile" class="btn btn-success" :disabled="!currentFile.content || loading">
        💾 导出文件
      </button>
      <button @click="clearContent" class="btn btn-warning" :disabled="!currentFile.content">
        🗑️ 清空内容
      </button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>处理中...</p>
    </div>

    <!-- 文件信息 -->
    <div v-if="currentFile.path" class="file-info">
      <h3>当前文件信息</h3>
      <div class="info-grid">
        <div class="info-item">
          <span class="label">文件名:</span>
          <span class="value">{{ currentFile.name }}</span>
        </div>
        <div class="info-item">
          <span class="label">路径:</span>
          <span class="value" :title="currentFile.path">{{ currentFile.path }}</span>
        </div>
        <div class="info-item">
          <span class="label">大小:</span>
          <span class="value">{{ formatFileSize(currentFile.size) }}</span>
        </div>
        <div class="info-item">
          <span class="label">修改时间:</span>
          <span class="value">{{ formatDate(currentFile.modified) }}</span>
        </div>
      </div>
    </div>

    <!-- 文本编辑器 -->
    <div class="editor-section">
      <div class="editor-header">
        <h3>文件内容</h3>
        <div class="editor-tools">
          <select v-model="fileType" @change="updateFileType" class="file-type-select">
            <option value="text">普通文本</option>
            <option value="json">JSON</option>
            <option value="markdown">Markdown</option>
          </select>
          <span class="char-count">字符数: {{ contentLength }}</span>
        </div>
      </div>
      
      <textarea
        v-model="currentFile.content"
        class="editor"
        :placeholder="placeholderText"
        @input="onContentChange"
      ></textarea>
    </div>

    <!-- 消息提示 -->
    <div v-if="message.text" :class="['message', message.type]">
      {{ message.text }}
    </div>

    <!-- 操作历史 -->
    <div v-if="history.length > 0" class="history">
      <h3>操作历史</h3>
      <ul class="history-list">
        <li v-for="(item, index) in history" :key="index" class="history-item">
          <span class="history-time">{{ formatTime(item.time) }}</span>
          <span class="history-action">{{ item.action }}</span>
          <span v-if="item.file" class="history-file">{{ item.file }}</span>
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'

// 响应式数据
const loading = ref(false)
const fileType = ref('text')
const currentFile = ref({
  path: '',
  name: '',
  content: '',
  size: 0,
  modified: null as Date | null
})

const message = ref({
  text: '',
  type: 'info' // 'info', 'success', 'error', 'warning'
})

const history = ref<Array<{
  time: Date,
  action: string,
  file?: string
}>>([])

// 计算属性
const contentLength = computed(() => currentFile.value.content.length)

const placeholderText = computed(() => {
  switch (fileType.value) {
    case 'json':
      return '请输入有效的JSON格式数据...\n例如:\n{\n  "name": "示例",\n  "value": 123\n}'
    case 'markdown':
      return '请输入Markdown格式文本...\n例如:\n# 标题\n\n这是一个**粗体**文本。'
    default:
      return '请输入或导入文件内容...'
  }
})

// 方法
/**
 * 导入文件
 */
const importFile = async () => {
  loading.value = true
  showMessage('正在选择文件...', 'info')

  try {
    const result = await window.api.file.importFile()
    
    if (result.canceled) {
      showMessage('已取消导入', 'warning')
      return
    }

    if (result.success) {
      currentFile.value = {
        path: result.filePath || '',
        name: result.name || '',
        content: result.content || '',
        size: result.size || 0,
        modified: result.modified ? new Date(result.modified) : null
      }

      // 根据文件扩展名设置文件类型
      const extension = result.name?.split('.').pop()?.toLowerCase()
      if (extension === 'json') {
        fileType.value = 'json'
      } else if (extension === 'md') {
        fileType.value = 'markdown'
      } else {
        fileType.value = 'text'
      }

      addToHistory('导入文件', result.name || '未知文件')
      showMessage(`成功导入文件: ${result.name || '未知文件'}`, 'success')
    } else {
      showMessage(`导入失败: ${result.error}`, 'error')
    }
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error)
    showMessage(`导入出错: ${errorMessage}`, 'error')
  } finally {
    loading.value = false
  }
}

/**
 * 导出文件
 */
const exportFile = async () => {
  if (!currentFile.value.content.trim()) {
    showMessage('没有内容可以导出', 'warning')
    return
  }

  // JSON格式验证
  if (fileType.value === 'json') {
    try {
      JSON.parse(currentFile.value.content)
    } catch (error) {
      showMessage('JSON格式不正确，请检查后再导出', 'error')
      return
    }
  }

  loading.value = true
  showMessage('正在保存文件...', 'info')

  try {
    // 根据文件类型设置默认扩展名
    let defaultPath = 'export.txt'
    switch (fileType.value) {
      case 'json':
        defaultPath = 'export.json'
        break
      case 'markdown':
        defaultPath = 'export.md'
        break
    }

    const result = await window.api.file.exportFile(currentFile.value.content, {
      defaultPath
    })
    
    if (result.canceled) {
      showMessage('已取消导出', 'warning')
      return
    }

    if (result.success) {
      const fileName = result.filePath?.split(/[/\\]/).pop() || '未知文件'
      addToHistory('导出文件', fileName)
      showMessage(`成功导出到: ${fileName}`, 'success')
    } else {
      showMessage(`导出失败: ${result.error}`, 'error')
    }
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error)
    showMessage(`导出出错: ${errorMessage}`, 'error')
  } finally {
    loading.value = false
  }
}

/**
 * 清空内容
 */
const clearContent = () => {
  if (confirm('确定要清空所有内容吗？此操作不可撤销。')) {
    currentFile.value.content = ''
    addToHistory('清空内容')
    showMessage('已清空内容', 'info')
  }
}

/**
 * 内容变化处理
 */
const onContentChange = () => {
  // 可以在这里添加自动保存逻辑
}

/**
 * 更新文件类型
 */
const updateFileType = () => {
  addToHistory(`切换文件类型为: ${fileType.value}`)
}

/**
 * 显示消息
 */
const showMessage = (text: string, type: string = 'info') => {
  message.value = { text, type }
  // 3秒后自动清除消息
  setTimeout(() => {
    if (message.value.text === text) {
      message.value.text = ''
    }
  }, 3000)
}

/**
 * 添加到历史记录
 */
const addToHistory = (action: string, file?: string) => {
  history.value.unshift({
    time: new Date(),
    action,
    file
  })
  
  // 只保留最近10条记录
  if (history.value.length > 10) {
    history.value.pop()
  }
}

/**
 * 格式化文件大小
 */
const formatFileSize = (bytes: number): string => {
  if (!bytes) return '0 B'
  
  const units = ['B', 'KB', 'MB', 'GB']
  let size = bytes
  let unitIndex = 0
  
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024
    unitIndex++
  }
  
  return `${size.toFixed(1)} ${units[unitIndex]}`
}

/**
 * 格式化日期
 */
const formatDate = (date: Date | null): string => {
  if (!date) return '--'
  return new Date(date).toLocaleString('zh-CN')
}

/**
 * 格式化时间
 */
const formatTime = (date: Date): string => {
  return date.toLocaleTimeString('zh-CN')
}

// 组件挂载时初始化
onMounted(() => {
  showMessage('文件管理器已就绪', 'success')
})
</script>

<style scoped>
.file-manager {
  min-height: 100vh;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  box-sizing: border-box;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h2 {
  color: #2c3e50;
  margin: 0;
  font-size: 2.2em;
}

.subtitle {
  color: #7f8c8d;
  margin: 5px 0 0 0;
  font-size: 1.1em;
}

.actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
  min-width: 120px;
}

.btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-primary {
  background: linear-gradient(45deg, #3498db, #2980b9);
  color: white;
}

.btn-success {
  background: linear-gradient(45deg, #2ecc71, #27ae60);
  color: white;
}

.btn-warning {
  background: linear-gradient(45deg, #f39c12, #e67e22);
  color: white;
}

.loading {
  text-align: center;
  margin: 20px 0;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 10px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.file-info {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
  border-left: 4px solid #3498db;
}

.file-info h3 {
  margin: 0 0 15px 0;
  color: #2c3e50;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 10px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #ecf0f1;
}

.label {
  font-weight: 600;
  color: #34495e;
}

.value {
  color: #7f8c8d;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.editor-section {
  margin-bottom: 30px;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

.editor-header h3 {
  margin: 0;
  color: #2c3e50;
}

.editor-tools {
  display: flex;
  align-items: center;
  gap: 15px;
}

.file-type-select {
  padding: 6px 12px;
  border: 2px solid #bdc3c7;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.char-count {
  color: #7f8c8d;
  font-size: 0.9em;
}

.editor {
  width: 100%;
  min-height: 400px;
  padding: 20px;
  border: 2px solid #bdc3c7;
  border-radius: 8px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
  resize: vertical;
  background: #fafafa;
  transition: border-color 0.3s ease;
}

.editor:focus {
  outline: none;
  border-color: #3498db;
  background: white;
}

.message {
  padding: 12px 20px;
  border-radius: 6px;
  margin: 20px 0;
  font-weight: 500;
  border-left: 4px solid;
}

.message.info {
  background: #d1ecf1;
  color: #0c5460;
  border-color: #17a2b8;
}

.message.success {
  background: #d4edda;
  color: #155724;
  border-color: #28a745;
}

.message.error {
  background: #f8d7da;
  color: #721c24;
  border-color: #dc3545;
}

.message.warning {
  background: #fff3cd;
  color: #856404;
  border-color: #ffc107;
}

.history {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  border-left: 4px solid #6c757d;
}

.history h3 {
  margin: 0 0 15px 0;
  color: #2c3e50;
}

.history-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 8px 0;
  border-bottom: 1px solid #dee2e6;
}

.history-item:last-child {
  border-bottom: none;
}

.history-time {
  color: #6c757d;
  font-size: 0.9em;
  min-width: 80px;
}

.history-action {
  font-weight: 500;
  color: #495057;
}

.history-file {
  color: #007bff;
  font-style: italic;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .file-manager {
    padding: 15px;
  }
  
  .actions {
    flex-direction: column;
    align-items: center;
  }
  
  .btn {
    width: 100%;
    max-width: 200px;
  }
  
  .editor-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style>
